<?php

class ArmoryRunTask extends sfBaseTask
{
    protected function configure()
    {
        // // add your own arguments here
        // $this->addArguments(array(
        //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
        // ));

        $this->addOptions(array(
                new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
                new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
                new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
                //new sfCommandOption('file', null, sfCommandOption::PARAMETER_REQUIRED, 'LUA File to convert', 'data/RPBot.lua'),
                // add your own options here
        ));

        $this->namespace        = 'raidpoints';
        $this->name             = 'armory-run';
        $this->briefDescription = '';
        $this->detailedDescription = <<<EOF
The [armory-sync|INFO] task does things.
Call it with:

  [php symfony armory-sync|INFO]
EOF;
    }

    public function doLogSection($section, $message, $size = NULL, $style ='INFO')
    {
        global $totalCount;

        $q = Doctrine::getTable("DataSyncStatus")
                ->createQuery()
                ->orderBy("date desc")
                ->limit(1);
        $r = $q->execute();

        $is = new DataSyncStatus();
        $is->setDate(gmdate("Y-m-d H:i:s", time()));
        $is->setStatus($section);
        $is->setText($message);
        //$is->setStatustotal($totalCount);
        if (isset($size))
        {
            $is->setStatusbar($size);
            $is->setStatustotal($style);
            $style = 'INFO';
            $size = null;
        }
        $is->save();
        $this->logsection($section, $message, $size, $style);
    }

    protected function execute($arguments = array(), $options = array())
    {
        // initialize the database connection
        $databaseManager = new sfDatabaseManager($this->configuration);
        $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
        // add your code here
        $startTime = time();
        $r = null;
        $tree = array(
                0 => "treeOne",
                1 => "treeTwo",
                2 => "treeThree",
        );
        $q = Doctrine::getTable("DataSync")
                ->createQuery()
                ->select('process, value')
                ->limit(1);
        $r = $q->execute();
        while($r->count() > 0)
        {
            foreach ($r as $sd)
            {
                if ($sd['process'] == 'player')
                {
                    $value = unserialize($sd['value']);
                    $key = $value['key'];
                    $data = $value['data'];
                    //$count++;
                    $query = Doctrine::getTable("Player")
                            ->createQuery()
                            ->where("name=?", $key);
                    $result = $query->execute();

                    if ($data != null && $result->count() > 0)
                    {
                        $player = $result->getFirst();
                        if (isset($data["noarmory"]) && $data["noarmory"])
                        {
                            $data['talentid'] = $player['talentid'];
                        }
                        else
                        {
                            $xml = getArmoryDataXML("http://www.wowarmory.com/character-talents.xml?r=".rawurlencode(sfConfig::get("app_server"))."&cn=".rawurlencode(($key))."&rhtml=n");
                            $talentGroup = $xml->xpath("/page/characterInfo/talents/talentGroup");
                            foreach ($talentGroup as $g => $value)
                            {
                                $group = attribs($talentGroup[$g]);
                                $spec = $value->xpath("talentSpec");
                                $spec = attribs($spec[0]);

                                $pt = null;
                                $query = Doctrine::getTable("PlayerTalent")
                                        ->createQuery()
                                        ->where("playerid=?", $player->getId())
                                        ->andWhere("talentgroup=?", $group["group"]);
                                $result = $query->execute();
                                if ($result->count() > 0)
                                    $pt = $result->getFirst();
                                else
                                {
                                    $pt = new PlayerTalent();
                                    $pt->setPlayerid($player->getId());
                                    if ($group["group"] == 1)
                                        $pt->setMainspec(1);
                                }
                                $pt->setTalentgroup($group["group"]);
                                $pt->setActive(@($group["active"]? 1 : 0));
                                $pt->setSpec($spec[$tree[0]]."/".$spec[$tree[1]]."/".$spec[$tree[2]]);
                                $pt->setUrl($spec["value"]);

                                $max = 0;
                                $id = 3;
                                for ($i = 0; $i < 3; $i++)
                                {
                                    if ($spec[$tree[$i]] > $max)
                                    {
                                        $max = $spec[$tree[$i]];
                                        $id = $i;
                                    }
                                }

                                $query = Doctrine::getTable("Talent")
                                        ->createQuery()
                                        ->where("classid=?", $player->getClassid())
                                        ->addWhere("talentid=?", $id);
                                $result = $query->execute();
                                if ($result->count() > 0)
                                {
                                    //$player->setTalent($result->getFirst());
                                    //$player->save();
                                    $pt->setTalent($result->getFirst());
                                    $perc = 0;
                                    $this->doLogSection("Working", " -- Player: ".utf8_decode($player["name"])." ID: ".$player["id"]." Talent: ".$result->getFirst()->getName(), $perc, 100)  ;
                                }
                                $pt->save();
                            }
                        }

                    }
                }
                $sd->delete();
            }
            if ($startTime+20 < time())
            {
                $bg = new BackgroundIt();
                $bg->run(sfConfig::get('sf_root_dir').'/symfony raidpoints:armory-run', sfConfig::get("app_path_to_php"));
                exit();
            }
            $r = $q->execute();
        }

        $this->doLogSection("Working", " ------ Phase 3 ------", 100, 100);
        $this->doLogSection("Working", " --- Points Update ---", 100, 100);
        Doctrine::getTable("PlayerHistory")->updatePoints();
        $this->doLogSection("Finished", "Finished data armory-sync!", 100, 100);
        sleep(2);
        $is = new DataSyncStatus();
        $is->setDate(gmdate("Y-m-d H:i:s", time()));
        $is->setStatus("Ready");
        $is->setText("Ready for next import.");
        $is->setStatustotal(0);
        $is->setStatusbar(0);
        $is->save();
    }
}
